import { Injectable } from "@nestjs/common";
import { In, Like, Repository } from "typeorm";
import { ResultData } from "@/common/utils/result";
import { instanceToPlain } from "class-transformer";
import { InjectRepository } from "@nestjs/typeorm";
import { SysConfig } from "@/modules/sys-config/entities/sys-config.entity";

@Injectable()
export class SysConfigService {
    
    constructor(
        @InjectRepository(SysConfig)
        private readonly SysConfigRepository: Repository<SysConfig>
    ) {
    }
    
    
    async create(createDto) {
        return ResultData.ok(instanceToPlain(await this.SysConfigRepository.save(createDto)));
    }
    
    async findAll(findAllDto) {
        const { page, size, username, status } = findAllDto;
        const take = size || 15;
        const skip = ((page || 1) - 1) * take;
        const where = {
            ...(status === 0 || status ? { status } : null),
            ...(username ? { username: Like(`%${username}%`) } : null)
        };
        return ResultData.rowOk(instanceToPlain(await this.SysConfigRepository.findAndCount({
            order: {
                id: "DESC"
            },
            // where,
            skip,
            take
        })));
    }
    
    async findOne(id: number) {
        return ResultData.ok(instanceToPlain(await this.SysConfigRepository.findOneById(id)));
    }
    
    async findOneByAppType(appType: number) {
        return ResultData.ok(instanceToPlain(await this.SysConfigRepository.findOne({
            where: { appType }
        })));
    }
    
    async update(id: number, updateDto) {
        console.log("updateDto", updateDto);
        return ResultData.ok(await this.SysConfigRepository.update(id, updateDto), "更新成功");
    }
    
    async removeByIds({ ids }) {
        return ResultData.ok(await this.SysConfigRepository.delete({ id: In(ids) }), "删除成功");
    }
    
    async remove(id: number) {
        return ResultData.ok(await this.SysConfigRepository.delete(id), "删除成功");
    }
}
